package com.phospherus.flow.service

import com.phospherus.user.entity.User
import org.apache.commons.lang.StringUtils
import org.hibernate.SQLQuery
import org.hibernate.transform.Transformers
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageImpl
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Service
import java.math.BigInteger
import javax.persistence.EntityManager


/**
 * @author songjinlong
 * @version 1.0
 * @since 2017/12/26
 */
@Service
class FormQueryService {
    @Autowired
    lateinit var em: EntityManager

    fun getToDoLit(map: Map<String, Any>): Page<Map<String, String>> {
        var user = map["USER"] as User
        var orderCode = check(map["orderCode"] as String?)
        var ftcCode = check(map["ftcCode"] as String?)
        var buyerName = check(map["buyerName"] as String?)
        var currPage = check(map["currPage"] as String?)?.toInt() ?: 0
        var pageSize = check(map["pageSize"] as String?)?.toInt() ?: 20

        var limit = check(map["limit"] as String?)
        //fixme 按到达时间查询暂时不做
//        var arrivalTime = (map["arrivalTime"] as String?)?.toLong()
        var countSql = "select count(*) "
        var selectSql = "select wfi.curr_node_id, wfi.arrival_time,wfi.finish_time,fi.*"
        var fromSql = "from work_flow_inst wfi,form_inst fi,flow f "
        var whereSql = "where wfi.work_flow_type=1 and fi.id=wfi.form_inst_id and f.id=fi.flow_id " +
                "and curr_user_id=${user.id} " +
                if (StringUtils.isNotBlank(orderCode)) {
                    "and fi.order_code='$orderCode'"
                } else {
                    ""
                } +
                if (StringUtils.isNotBlank(ftcCode)) {
                    "and fi.ftc_code = '$ftcCode'"
                } else {
                    ""
                } +
                if (StringUtils.isNotBlank(buyerName)) {
                    "and fi.buyer_name = '$buyerName'"
                } else {
                    ""
                }
        var selectQuery = em.createNativeQuery(selectSql + fromSql + whereSql)
        selectQuery.unwrap(SQLQuery::class.java).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
        val pageRequest: Pageable = PageRequest(currPage, pageSize)
        selectQuery.firstResult = pageRequest.offset
        selectQuery.maxResults = pageRequest.pageSize
        var countQuery = em.createNativeQuery(countSql + fromSql + whereSql)
        var total = (countQuery.singleResult as BigInteger).toLong()
        return PageImpl(selectQuery.resultList as List<Map<String, String>>, pageRequest, total)
    }

    /**
     * 替换sql中 ' ; -- 符号 初步防止sql注入
     */
    fun check(sql: String?): String? = sql?.replace("([';])+|(--)+", "");
}